package pl.gladiator.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import pl.gladiator.ftp.FTPManager;
import pl.gladiator.model.Album;
import pl.gladiator.model.Gallery;
import pl.gladiator.model.Newsy;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileItemFactory;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;

@Controller
@RequestMapping("/gallery")
public class GalleryController {

	@RequestMapping(method = RequestMethod.GET)
	public String displayAll(HttpServletRequest request) {
		FTPManager ftpManager = new FTPManager();
		List<Gallery> albumList = ftpManager.getAlbumsNames();
		if (!albumList.isEmpty()) {
			request.setAttribute("albumList", albumList);
		}
		return "albums";
	}

	@RequestMapping(value = "/showAlbums", method = RequestMethod.GET)
	public String showAlbums(HttpServletRequest request) {
		FTPManager ftpManager = new FTPManager();
		List<Gallery> albumList = ftpManager.getAlbumsNames();
		if (!albumList.isEmpty()) {
			request.setAttribute("albumList", albumList);
		}
		return "albums";
	}
	
	@RequestMapping(value = "/showAlbum/{albumName}")
	public String displayPath(@PathVariable String albumName,
			HttpServletRequest request) {
		FTPManager ftpManager = new FTPManager();
		List<Gallery> fileList = ftpManager.getFileNamesFromAlbum(albumName);
		if (!fileList.isEmpty()) {
			request.setAttribute("fileList", fileList);
			request.setAttribute("albumName", albumName);
		}
		return "pictures";
	}

	@RequestMapping(value = "/addAlbum", method = RequestMethod.GET)
	public ModelAndView addAlbum() {
		Album album = new Album();
		ModelMap map = new ModelMap();
		map.put("album", album);
		return new ModelAndView("addAlbum", map);

	}
	
	@RequestMapping(value = "/addPictures", method = RequestMethod.GET)
	public String addPictures(Album album, BindingResult errors, HttpServletRequest request, HttpServletResponse response) {
		request.setAttribute("albumName", album.getAlbumName());
		request.setAttribute("quantity", album.getQuantity());
		HttpSession session = request.getSession();
		session.setAttribute("albumName", album.getAlbumName());
		return "addPictures";

	}
	
	@RequestMapping(value = "/addPictures2", method = RequestMethod.POST)
	public String addPictures2(HttpServletRequest request, HttpServletResponse response){
		FTPManager ftpManager = new FTPManager();
			boolean isMultipart = ServletFileUpload.isMultipartContent(request);
	        if (isMultipart) {
	            FileItemFactory factory = new DiskFileItemFactory();
	            ServletFileUpload upload = new ServletFileUpload(factory);
	            
	            try {
	            	ftpManager.connectToFTPServer();
	            	HttpSession session = request.getSession();
	            	String albumName = (String) session.getAttribute("albumName");
	            	ftpManager.createDirectory(FTPManager.directory+"/"+albumName+"/");
	                List items = upload.parseRequest(request);
	                Iterator iterator = items.iterator();
	                while (iterator.hasNext()) {
	                    FileItem item = (FileItem) iterator.next();
	                    if (!item.isFormField()) {
	                        String fileName = item.getName();
	                        String root = request.getServletContext().getRealPath("/");
	                        File path = new File(root + "/uploads");
	                        if (!path.exists()) {
	                            boolean status = path.mkdirs();
	                        }
	                        File uploadedFile = new File(path +"/" + fileName);
	                        System.out.println(uploadedFile.getAbsolutePath());
	                        try{
	                        	item.write(uploadedFile);
	                        	ftpManager.upload(uploadedFile, "");
	                        }catch (FileNotFoundException e) {
								System.out.println("Wyjatek " + e);
							}
	                    }
	                }
	                ftpManager.disconnectFromFTP();
	            } catch (FileUploadException e) {
	                e.printStackTrace();
	            } catch (Exception e) {
	                e.printStackTrace();
	            }
	        }
	        
			return "hello";
	}

}
